package com.ly.common.running.handler;

import com.ly.common.business.util.SpringContextUtil;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luoyana
 * @version V1.0
 * @ClassName ExtraFactory
 * @description
 * @update 2023/3/10
 */
@Service
public class ExtraFactory implements ApplicationListener {
    private static final Class<IExecuteFlow>[] extraTypes = new Class[]{IPeHandler.class};

    private static Map<String, List<IExecuteFlow>> exFlowMap;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        for(Class<IExecuteFlow> exeClass : extraTypes){
            exFlowMap.put(exeClass.getName(),initEffectiveExtra(exeClass));
        }
    }

    public ExtraFactory() {
        exFlowMap = new HashMap<>();
    }

    private <T extends IExecuteFlow> List<T> initEffectiveExtra(Class<T> e){
        Map<String,T> map = SpringContextUtil.applicationContext.getBeansOfType(e);
        List<T> traceList = new ArrayList<>(map.values());
        return traceList.stream().filter(var->var.isEffect()).collect(Collectors.toList());
    }

    public static <T extends IExecuteFlow> List<T> getEffectiveExtra(Class<T> e){
        return (List<T>) exFlowMap.get(e.getName());
    }
}
